package com.pig4cloud.pig.ads.service.bd.impl;

import com.alibaba.fastjson.JSON;
import com.baidu.dev2.api.sdk.adgroupfeed.api.AdgroupFeedService;
import com.baidu.dev2.api.sdk.adgroupfeed.model.*;
import com.baidu.dev2.api.sdk.common.ApiErrorInfo;
import com.baidu.dev2.api.sdk.common.ApiRequestHeader;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.pig.mapper.bd.BdAdgroupMapper;
import com.pig4cloud.pig.ads.service.AdvertiserService;
import com.pig4cloud.pig.ads.service.bd.BdAdgroupService;
import com.pig4cloud.pig.api.entity.AccountToken;
import com.pig4cloud.pig.api.entity.bd.BdAdgroup;
import com.pig4cloud.pig.api.entity.bd.BdAdgroupReq;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author chengang
 * @Date 2022/12/21
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class BdAdgroupServiceImpl extends ServiceImpl<BdAdgroupMapper, BdAdgroup> implements BdAdgroupService {
    @Autowired
    private BdAdgroupMapper bdAdgroupMapper;

	private final AdvertiserService advertiserService;

    @Override
    public void saveUpdateList(List<BdAdgroup> list){

        List<Long> adgroupIds = list.stream().map(BdAdgroup::getAdgroupFeedId).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(adgroupIds)){
            return;
        }
        List<BdAdgroup> adgroupList = bdAdgroupMapper.getListByAdgroupIds(adgroupIds);
        list.forEach(a-> adgroupList.forEach(c->{
            if (c.getAdgroupFeedId().equals(a.getAdgroupFeedId())) {
                a.setId(c.getId());
                a.setSoucreStatus(c.getSoucreStatus());
            }
        }));

        this.saveOrUpdateBatch(list,1000);

    }


	/**
	 * 广告计划修改出价
	 * @param req
	 * @return
	 */
	@Override
	public R updateBid(BdAdgroupReq req) {
		ApiRequestHeader header = new ApiRequestHeader();
		try {
			AccountToken bdAccountToken = advertiserService.getAdvertiserToken(PlatformTypeEnum.BD.getValue(),req.getAdvertiserId().toString());
			if (Objects.isNull(bdAccountToken)) {
				return R.failed("百度广告账户Token已失效");
			}
			BdAdgroup bdAdgroup = baseMapper.selectOne(Wrappers.<BdAdgroup>lambdaQuery()
					.eq(BdAdgroup::getDeleted, 0)
					.eq(BdAdgroup::getAdgroupFeedId,req.getAdgroupFeedId()));
			if (Objects.isNull(bdAdgroup)) {
				return R.failed("百度当前广告计划不存在 !");
			}
			AdgroupFeedService adgroupFeedService = new AdgroupFeedService();
			UpdateAdgroupFeedRequestWrapper wrapper = new UpdateAdgroupFeedRequestWrapper();
			header.setAccessToken(bdAccountToken.getAccessToken());
			//注意这里传用户名，不是用户ID
			header.setUserName(bdAccountToken.getAdvertiserName());
			wrapper.setHeader(header);
			UpdateAdgroupFeedRequestWrapperBody body = new UpdateAdgroupFeedRequestWrapperBody();
			List<AdgroupFeedType> list = new ArrayList<>();
			AdgroupFeedType updateAdGroup = new AdgroupFeedType();
			if(bdAdgroup.getBidtype() == 3){
				OcpcType ocpc = JSON.parseObject(bdAdgroup.getOcpc(),OcpcType.class);
				ocpc.setOcpcBid(req.getCpaBid());
				list.add(updateAdGroup.adgroupFeedId(req.getAdgroupFeedId()).ocpc(ocpc));
				bdAdgroup.setOcpc(JSON.toJSONString(ocpc));
			}else {
				list.add(updateAdGroup.adgroupFeedId(req.getAdgroupFeedId()).bid(req.getCpaBid()));
				bdAdgroup.setBid( BigDecimal.valueOf(req.getCpaBid()));
			}
			body.setAdgroupFeedTypes(list);
			wrapper.body(body);
			UpdateAdgroupFeedResponseWrapper responseWrapper = adgroupFeedService.updateAdgroupFeed(wrapper);
			if (StringUtils.equals(responseWrapper.getHeader().getDesc(), "success")) {
				//修改数据表:更新出价信息
				this.baseMapper.updateById(bdAdgroup);
				return R.ok(">>>>>>百度修改广告计划出价成功");
			} else {
				List<String> mg = responseWrapper.getHeader().getFailures().stream().map(ApiErrorInfo::getMessage).collect(Collectors.toList());
				log.error(">>>>>>百度修改广告计划出价异常：" + JSON.toJSONString(responseWrapper));
				return R.failed(JSON.toJSONString(mg));
			}
		} catch (Exception e) {
			log.error(">>>>>>百度修改广告计划出价异常：" + e.getMessage());
			e.printStackTrace();
			return R.failed(">>>>>>百度修改广告计划出价异常");
		}
	}
	@Override
	public R getPutStatus(Set<Long> adIdSet) {
		List<BdAdgroup> list = baseMapper.selectList(Wrappers.<BdAdgroup>lambdaQuery().select(BdAdgroup::getAdgroupFeedId, BdAdgroup::getPause).in(BdAdgroup::getAdgroupFeedId, adIdSet));
		return R.ok(list);
	}
}
